<template>
  <a-card
    class="box-card"
    :bordered="false"
    :body-style="{
      padding: '12px',
      overflow: design ? 'hidden' : 'auto',
      borderRadius: '4px',
      position: 'absolute',
      top: '0',
      bottom: '0px',
      left: '0px',
      right: '0px'
    }"
  >
    <div class="box-card-body">

      <ViewRedirect v-if="element.type === 'table'"
                    v-show="design || element.showRules !== 'showAfterFks' || element.showRulesResult"
                    :viewCode="element.code"
                    :relationStatus="element.relationStatus"
                    :relationOpenFks="element.relationOpenFks"
                    :relationList="relationList"
                    :subViews="subViews"
                    :stores="stores"
                    v-bind="$attrs"
                    v-on="$listeners">
      </ViewRedirect>

      <ViewEditableRedirect v-else-if="element.type === 'editableTable'"
                    v-show="design || element.showRules !== 'showAfterFks' || element.showRulesResult"
                    :viewCode="element.code"
                    :relationStatus="element.relationStatus"
                    :relationOpenFks="element.relationOpenFks"
                    :relationList="relationList"
                    :subViews="subViews"
                    :stores="stores"
                    v-bind="$attrs"
                    v-on="$listeners">
      </ViewEditableRedirect>

      <TreeRedirect v-else-if="element.type === 'tree'"
                    v-show="design || element.showRules !== 'showAfterFks' || element.showRulesResult"
                    :viewCode="element.code"
                    :relationStatus="element.relationStatus"
                    :relationOpenFks="element.relationOpenFks"
                    :relationList="relationList"
                    :subViews="subViews"
                    :stores="stores"
                    v-bind="$attrs"
                    v-on="$listeners" >
      </TreeRedirect>

      <ReportWidgetRedirect v-else-if="element.type === 'report'"
                            :widgetCode="element.code"
                            :relationList="relationList"
                            :stores="stores"
                            v-bind="$attrs"
                            v-on="$listeners">
      </ReportWidgetRedirect>

      <BpmForm v-else-if="element.type === 'form' && bpmOption && element.flowForm === 'Y'"
               :formCode="element.code"
               :layoutCode="bpmOption.formCode"
               :relationStatus="element.relationStatus"
               :relationOpenFks="element.relationOpenFks"
               :relationList="relationList"
               :stores="stores"
               :showCloseBut="bpmOption.showCloseBut"
               :bpmId="bpmOption.bpmId"
               :bpmIdType="bpmOption.bpmIdType"
               :processInstanceId="bpmOption.processInstanceId"
               :processDefId="bpmOption.processDefId"
               :formId="bpmOption.formId"
               :fks="bpmOption.fks"
               :parentValue="bpmOption.parentValue"
               :buttonDatas="bpmOption.buttonDatas"
               :getBpmOperateVoUrl="bpmOption.getBpmOperateVoUrl"
               :processInstanceName="bpmOption.processInstanceName"
               v-on="$listeners"
               v-bind="$attrs"/>

      <FormRedirect v-else-if="element.type === 'form'"
                    :formCode="element.code"
                    :relationStatus="element.relationStatus"
                    :relationOpenFks="element.relationOpenFks"
                    :hiddenSaveBut="element.saveBut === 'display'"
                    :func="design ? 'add' : (element.formStatus === 'auto' ? ((element.mainForm !== 'N' && formOption) ? formOption.func : 'add') : (element.formStatus === 'disabled' ? 'detail' : 'edit'))"
                    :formId="(element.mainForm !== 'N' && formOption) ? formOption.formId : undefined"
                    :fks="(element.mainForm !== 'N' && formOption) ? formOption.fks : undefined"
                    :parentValue="(element.mainForm !== 'N' && formOption) ? formOption.parentValue : undefined"
                    :saveInPage="(element.mainForm !== 'N' && formOption) ? formOption.saveInPage : undefined"
                    :disQueryDB="(element.mainForm !== 'N' && formOption) ? formOption.disQueryDB : undefined"
                    :record="(element.mainForm !== 'N' && formOption) ? formOption.record : undefined"
                    :isTab="formOption ? formOption.isTab : undefined"
                    :relationList="relationList"
                    :stores="stores"
                    v-bind="$attrs"
                    @close="$emit('closeFromView')"
                    @hideDialogButtons="$emit('hideDialogButtonsFromView')"
                    @addParentSpinning="$emit('addParentSpinningFromView')"
                    @delParentSpinning="$emit('delParentSpinningFromView')"
                    @handleOk="handleOkFromView"
                    @setFormTitle="setFormTitleFromView"
                    v-on="$listeners">
      </FormRedirect>

      <a-tabs v-else-if="element.type === 'tabs'" :type="design ? 'editable-card' : 'line'" @edit="onEdit"
              :tab-bar-style="!design && element.affixTabs ? tabBarStyle : {}"
              :style="!design && element.affixTabs ? tabStyle : {}"
              v-model="selectTab" @change="changeTabs">
        <a-tab-pane :tab="$locale(tab.title)" :key="tab.key" v-for="(tab, index) in element.tabs"
                    :closable="design && element.tabs.length > 1"
                    v-if="design || tab.showRules !== 'showAfterFks' || tab.showRulesResult">

          <ViewRedirect v-if="tab.type === 'table'"
                        :viewCode="tab.code"
                        :relationStatus="tab.relationStatus"
                        :relationOpenFks="tab.relationOpenFks"
                        :relationList="relationList"
                        :subViews="subViews"
                        :stores="stores"
                        :tab-config="tab"
                        v-bind="$attrs"
                        v-on="$listeners" >
          </ViewRedirect>

          <ViewEditableRedirect v-else-if="tab.type === 'editableTable'"
                        :viewCode="tab.code"
                        :relationStatus="tab.relationStatus"
                        :relationOpenFks="tab.relationOpenFks"
                        :relationList="relationList"
                        :subViews="subViews"
                        :stores="stores"
                        :tab-config="tab"
                        v-bind="$attrs"
                        v-on="$listeners" >
          </ViewEditableRedirect>

          <TreeRedirect v-else-if="tab.type === 'tree'"
                        :viewCode="tab.code"
                        :relationStatus="tab.relationStatus"
                        :relationOpenFks="tab.relationOpenFks"
                        :relationList="relationList"
                        :subViews="subViews"
                        :stores="stores"
                        :tab-config="tab"
                        v-bind="$attrs"
                        v-on="$listeners">
          </TreeRedirect>

          <ReportWidgetRedirect v-else-if="tab.type === 'report'"
                                :widgetCode="tab.code"
                                :relationList="relationList"
                                :stores="stores"
                                :tab-config="tab"
                                v-bind="$attrs"
                                v-on="$listeners">
          </ReportWidgetRedirect>

          <BpmForm v-else-if="tab.type === 'form' && bpmOption && tab.flowForm === 'Y'"
                   :formCode="tab.code"
                   :layoutCode="bpmOption.formCode"
                   :relationStatus="tab.relationStatus"
                   :relationOpenFks="tab.relationOpenFks"
                   :relationList="relationList"
                   :stores="stores"
                   :tab-config="tab"
                   :showCloseBut="bpmOption.showCloseBut"
                   :bpmId="bpmOption.bpmId"
                   :bpmIdType="bpmOption.bpmIdType"
                   :processInstanceId="bpmOption.processInstanceId"
                   :processDefId="bpmOption.processDefId"
                   :formId="bpmOption.formId"
                   :fks="bpmOption.fks"
                   :parentValue="bpmOption.parentValue"
                   :buttonDatas="bpmOption.buttonDatas"
                   :getBpmOperateVoUrl="bpmOption.getBpmOperateVoUrl"
                   :processInstanceName="bpmOption.processInstanceName"
                   v-on="$listeners"
                   v-bind="$attrs"/>

          <FormRedirect v-else-if="tab.type === 'form'"
                        :formCode="tab.code"
                        :relationStatus="tab.relationStatus"
                        :relationOpenFks="tab.relationOpenFks"
                        :hiddenSaveBut="tab.saveBut === 'display'"
                        :func="design ? 'add' : (tab.formStatus === 'auto' ? ((tab.mainForm !== 'N' && formOption) ? formOption.func : 'add') : (tab.formStatus === 'disabled' ? 'detail' : 'edit'))"
                        :formId="(tab.mainForm !== 'N' && formOption) ? formOption.formId : undefined"
                        :fks="(tab.mainForm !== 'N' && formOption) ? formOption.fks : undefined"
                        :parentValue="(tab.mainForm !== 'N' && formOption) ? formOption.parentValue : undefined"
                        :saveInPage="(tab.mainForm !== 'N' && formOption) ? formOption.saveInPage : undefined"
                        :disQueryDB="(tab.mainForm !== 'N' && formOption) ? formOption.disQueryDB : undefined"
                        :record="(tab.mainForm !== 'N' && formOption) ? formOption.record : undefined"
                        :isTab="formOption ? formOption.isTab : undefined"
                        :relationList="relationList"
                        :stores="stores"
                        :tab-config="tab"
                        v-bind="$attrs"
                        @close="$emit('closeFromView')"
                        @hideDialogButtons="$emit('hideDialogButtonsFromView')"
                        @addParentSpinning="$emit('addParentSpinningFromView')"
                        @delParentSpinning="$emit('delParentSpinningFromView')"
                        @handleOk="handleOkFromView"
                        @setFormTitle="setFormTitleFromView"
                        v-on="$listeners">
          </FormRedirect>

          <template v-if="design">
            <draggable
              v-show="!tab.type"
              style="height: 300px; z-index: 9;"
              v-model="element.tabs"
              v-bind="{ group: 'people', ghostClass: 'ghost', animation: 200, handle: '.drag-widget' }"
              @add="handleWidgetAdd"
            >
              <div class="fm-widget-form-empty"
                   style="height: 300px; width: 100%; top: 50px; left: 0; margin: 0; z-index: 9;">
                {{$t('m.eform.formDesign.label.dragModel')}}
              </div>
            </draggable>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-card>
</template>

<script>

import YchConstant from "@/api/YchConstant";
import ViewRedirect from "../redirect/ViewRedirect";
import ViewEditableRedirect from "../redirect/ViewEditableRedirect";
import ReportWidgetRedirect from "../redirect/ReportWidgetRedirect";
import TreeRedirect from "../redirect/TreeRedirect";
import FormRedirect from "../redirect/FormRedirect";
import BpmForm from "../redirect/BpmForm";
import {randomString} from "../../../utils/util";
import Draggable from 'vuedraggable';
import RelationUtil from "../redirect/RelationUtil";

export default {
  name: 'LayoutCardContainer',
  props: {
    element: Object,
    data: Object,
    subViews: {
      type: Object,
      default: () => {
        return {}
      }
    },
    design: {
      type: Boolean,
      default: false
    },
    stores: {
      type: Object,
      default: () => {
        return {}
      }
    },
    formOption: Object,
    bpmOption: Object,
    relationList: Array,
  },
  components: {
    ViewRedirect,
    ReportWidgetRedirect,
    TreeRedirect,
    FormRedirect,
    BpmForm,
    ViewEditableRedirect,
    Draggable,
  },
  data() {
    return {
      selectTab: this.element.tabs ? this.element.tabs[0].key : null,
      url: {
        getViewModel: YchConstant.PREFIX_EFORM + '/engine/viewEngine/getViewModel',
      },
      tabBarStyle: {
        position: 'fixed',
        top: '0px',
        zIndex: '999',
        backgroundColor: 'white',
        width: '100%'
      },
      tabStyle: {
        marginTop: '44px',
      },
    }
  },
  methods: {
    onEdit(targetKey, action) {
      if (action === "add") {
        const tab = {
          title: 'm.eform.formDesign.label.Tab',
          key: randomString(32),
        };
        this.element.tabs.push(tab);
      } else if (action === "remove") {
        let index = 0;
        for (let i = 0; i < this.element.tabs.length; i++) {
          if (this.element.tabs[i].key === targetKey) {
            index = i;
            break;
          }
        }
        this.element.tabs.splice(index, 1);
        if (this.selectTab === targetKey) {
          this.selectTab = this.element.tabs[0].key
        }
      }
    },
    handleWidgetAdd(evt) {
      let newIndex = evt.newIndex;
      if (this.element.tabs.length === 1) {
        newIndex = 0;
      }
      const lastItem = this.element.tabs.splice(newIndex, 1);
      const target = lastItem[0];
      for (let i = 0; i < this.element.tabs.length; i++) {
        if (this.element.tabs[i].key === this.selectTab) {
          target.key = this.selectTab;
          this.element.tabs[i] = target
          break;
        }
      }
      const listString = JSON.stringify(this.element.tabs);
      this.element.tabs = JSON.parse(listString);
    },
    changeTabs(activeKey) {
      this.selectTab = activeKey
    },
    setFormTitleFromView(title) {
      this.$emit('setFormTitleFromView', title)
    },
    handleOkFromView($vue,isDraft){
      this.$emit('handleOkFromView', $vue,isDraft)
    },
    relationTable(table) {
      if (table.showRules === 'showAfterFks') {
        let tableName = null
        if (this.subViews && this.subViews[table.code]) {
          const result = this.subViews[table.code]
          tableName = result.tableShow.tableName
        }

        const fks = RelationUtil.getChangedRelation({
          relationList: this.relationList,
          tableName: tableName,
          fks: [],
          relationOpenFks: table.relationOpenFks,
        })
        table.showRulesResult = RelationUtil.checkFks({
          fks: fks,
        })
      }
    },
    relationTree(tree) {
      if (tree.showRules === 'showAfterFks') {
        let tableName = null
        if (this.subViews && this.subViews[tree.code]) {
          const result = this.subViews[tree.code]
          const treeData = result.treeData ? JSON.parse(result.treeData) : {}
          if (treeData.type === '1') {
            //普通模式
            const config = treeData.data || {}
            tableName = config.tableName
          } else {
            if (treeData.data.length > 0) {
              tableName = treeData.data[0].tableName
            }
          }
        }

        const fks = RelationUtil.getChangedRelation({
          relationList: this.relationList,
          tableName: tree.tableName,
          fks: [],
          relationOpenFks: tree.relationOpenFks,
        })
        const b = RelationUtil.checkFks({
          fks: fks,
        })
        tree.showRulesResult = b
      }
    }
  },
  watch: {
    selectTab: {
      handler(value) {
        if (this.element.type === 'tabs') {
          this.element.selectTab = value
        }
      },
      immediate: true
    },
    relationList: {
      handler() {
        if (this.design) {
          return
        }
        if (this.element.type === 'table' || this.element.type === 'editableTable') {
          this.relationTable(this.element);
        } else if (this.element.type === 'tree') {
          this.relationTree(this.element);
        } else if (this.element.type === 'tabs') {
          let currentIndex = -1;
          let index = -1;
          this.element.tabs.forEach(tab => {
            if (tab.showRules !== 'showAfterFks' || tab.showRulesResult) {
              if (currentIndex === -1) {
                index++
              }
              if (tab.key === this.selectTab) {
                currentIndex = index
              }
            }
            if (tab.type === 'table' || tab.type === 'editableTable') {
              this.relationTable(tab);
            } else if (tab.type === 'tree') {
              this.relationTree(tab);
            }
          })
          // 当前页签隐藏，切换到其他显示的页签
          const tabs = this.element.tabs.filter(tab => tab.showRules !== 'showAfterFks' || tab.showRulesResult)
          const currentTab = tabs.find(tab => tab.key === this.selectTab)
          if (!currentTab) {
            if (currentIndex === -1 || tabs.length <= currentIndex) {
              this.selectTab = tabs.length > 0 ? tabs[0].key : null
            } else {
              this.selectTab = tabs[currentIndex].key
            }
          }
        }
      },
      immediate: true
    },
  }
};
</script>

<style lang="less" scoped>
.box-card {
  position: relative;

  ::-webkit-scrollbar-thumb {
    border-width: 12px 0 0 12px !important;
  }

  .box-card-body {
    //height: 100%;
  }
}
</style>
